﻿using System;
using System.IO;

namespace Zjh.PackSerializer.Converters
{
    public class PackContractConverter : PackConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return PackContractMap.ContainsKey(objectType);
        }

        public override bool Read(Stream stream, Type objectType, IPackSerializer serializer, out object output)
        {
            output = Activator.CreateInstance(objectType);
            var pc = PackContractMap[objectType];
            foreach (var member in pc)
            {
                var obj = serializer.Deserialize(stream, member.MemberType);
                member.SetValue(output, obj);
            }
            return true;
        }

        public override bool Write(Stream stream, Type objectType, object input, IPackSerializer serializer)
        {
            var pc = PackContractMap[objectType];
            foreach (var member in pc)
            {
                var value = member.GetValue(input);
                serializer.Serialize(stream, member.MemberType, value);
            }
            return true;
        }
    }
}